var express = require('express');
var router = express.Router();
const crypto = require('crypto');
var multiparty = require('multiparty');
var { existingEvidenceModel, existingEviTypeModel, fileTypesModel, packageModel, ovTypeModel, obtainEvidenceModel, orderModel, } = require('../models/zq');
const { codeidModel, LoginModel, enterpriseCertificationModel } = require('../models/zhh');
const { identity } = require('lodash');
/* GET users listing. */

router.get('/add', (req, res) => {
  // // 存证类型   existingEviTypeModel
  // let eetype = [{ name: '司法存证' }, { name: '普通存证' }]
  // existingEviTypeModel.insertMany(eetype).then(() => {
  //   console.log('existingEviType批量插入成功');
  // })

  // // 文件类型   fileTypesModel
  // let fileType = [{ name: '图片文件' }, { name: '视频文件' }]
  // fileTypesModel.insertMany(fileType).then(() => {
  //   console.log('fileTypes批量插入成功');
  // })

  // // 用户   LoginModel
  // LoginModel.create({
  //   username: 'admin',
  //   password: '123456',
  //   phone: 17331963869,
  //   role: '管理员',
  // })

  res.send({ data: {} })
})

// 存证
router.get('/eels', async function (req, res, next) {
  let data = await existingEviTypeModel.find()
  res.send({
    code: 200,
    data
  })
});

//新增存证
router.post('/addDeposit', async function (req, res, next) {
  let body = req.body

  let maxheight = await existingEvidenceModel.findOne().sort('-height');
  console.log(maxheight);
  let mmaxheight;
  if (maxheight == null) {
    console.log(1);
    mmaxheight = 0
  } else {
    mmaxheight = maxheight.height
  }
  const hash = crypto.createHash('sha256');
  hash.update(body.name);

  // 计算哈希值
  const sha256Hash = hash.digest('hex');
  console.log('SHA-256哈希值:', sha256Hash);

  let Parenthash = await existingEvidenceModel.findOne({ height: mmaxheight })
  console.log(Parenthash, '494949494949');

  let Father = ''
  if (mmaxheight == 0) {
    Father = null
  } else {
    Father = Parenthash.eeHash
  }
  let filetype = ''
  if (body.fileType.substr(-3, 3) == 'png' || (body.fileType.substr(-3, 3) == 'jpg')) {

    let filetypeID = await fileTypesModel.findOne({ name: '图片文件' })
    console.log(filetypeID, '52156165153213201265210560215612561');
    let typeId = filetypeID._id
    console.log(typeId, '1321312312312312');
    filetype = String(typeId)
  } else {
    let filetypeID = await fileTypesModel.findOne({ name: '视频文件' });
    let typeId = filetypeID._id
    filetype = String(typeId)
  }

  let data = [
    {
      name: body.name, //存证名称
      type: body.type,//存证类型
      stats: 2,//状态
      fileType: filetype,//文件类型,
      fileName: body.fileType,//文件名称
      fileSize: 15.76,//文件大小
      height: mmaxheight + 1, //区块高度
      fileHash: sha256Hash, //文件哈希
      eeHash: '',//存证哈希也是头哈希
      fatherHash: Father, //父哈希
      is3D: Boolean(body.is3D),
    }
  ]

  console.log(data);
  let adddata = await existingEvidenceModel.create(data)
  const uphash = crypto.createHash('sha256');

  uphash.update(toString(adddata._id));
  const eeHashHash = uphash.digest('hex');
  console.log(eeHashHash, 'eeHashHash');

  let addbefortedate = await existingEvidenceModel.findOne({ fileHash: sha256Hash })
  console.log(addbefortedate._id, 'addid');

  let updatedata = await existingEvidenceModel.updateOne({ _id: addbefortedate._id }, { eeHash: eeHashHash })
  console.log(updatedata, 'updatedata');
  console.log(adddata, 'adddata');

  let datas = await existingEvidenceModel.find()
  res.send({
    code: 200,
    datas,
    msg: '添加成功'
  })


})

//查看存证信息
router.get('/getexistingEvidence', async function (req, res) {
  let body = req.query
  console.log(body);
  let { name, fileName, time } = body
  // console.log(time);
  let schema = {}
  if (name) {
    schema.name = new RegExp(name)
  }
  if (fileName) {
    schema.fileName = new RegExp(fileName)
  }
  if (time) {
    time = time.split(',')
    schema.createTime = { $gte: new Date(time[0]), $lte: new Date(time[1]) }
  }
  console.log(schema);
  let data = await existingEvidenceModel.find(schema)
  res.send({
    code: 200,
    data,
    msg: "存证信息获取成功"
  })
})

//新增取证信息
router.post('/addovType', async function (req, res) {
  let body = req.body
  const hash = crypto.createHash('sha256');
  // 计算哈希值
  const sha256Hash = hash.digest('hex');
  let maxheight = await obtainEvidenceModel.findOne().sort('-height');
  console.log(maxheight, '148148148148148');
  let mmaxheight

  if (maxheight == null) {
    mmaxheight = 0
  } else {
    mmaxheight = maxheight.height
  }
  console.log(mmaxheight);
  let filetype = ''
  if (body.fileType.substr(-3, 3) == 'png' || (body.fileType.substr(-3, 3) == 'jpg')) {
    let filetypeID = await fileTypesModel.findOne({ name: '图片文件' })
    let typeId = filetypeID._id
    filetype = String(typeId)
  } else {
    let filetypeID = await fileTypesModel.findOne({ name: '视频文件' });
    let typeId = filetypeID._id
    filetype = String(typeId)
  }

  let fatherHash
  if (mmaxheight == 0) {
    console.log(0);
    fatherHash = null
  } else {
    fatherHash = await obtainEvidenceModel.findOne({ height: mmaxheight })
    // console.log(fatherHash);
    fatherHash = fatherHash.eeHash
  }
  console.log(mmaxheight, fatherHash);
  let data = [
    {
      name: body.name, //取证名称
      type: body.type,//取证类型
      stats: 2,//状态
      fileType: filetype,//文件类型,
      fileName: body.fileType,//文件名称
      fileSize: 15.76,//文件大小
      height: mmaxheight + 1, //区块高度
      fileHash: sha256Hash, //文件哈希
      eeHash: '',//取证哈希也是头哈希
      fatherHash: fatherHash, //父哈希
      is3D: Boolean(body.is3D),
    }
  ]
  await obtainEvidenceModel.create(data)
  let addovType = await obtainEvidenceModel.findOne({ height: mmaxheight + 1 })
  const uphash = crypto.createHash('sha256');

  console.log(addovType._id.toString());
  uphash.update(toString(addovType._id.toString()));
  const eeHashHash = uphash.digest('hex');
  console.log('eeHashHash', eeHashHash);
  let addbefortedate = await obtainEvidenceModel.findOne({ fileHash: sha256Hash })

  let updatedata = await obtainEvidenceModel.updateOne({ _id: addovType._id }, { eeHash: eeHashHash })
  console.log('updatedata', updatedata);
  let datas = await obtainEvidenceModel.find()
  res.send({
    code: 200,
    msg: '新增取证成功',
    datas
  })
})

//查看取证信息
router.get('/getobtainEvidence', async function (req, res) {
  let body = req.query
  console.log(body);
  let { name, fileName, time } = body
  // console.log(time);
  let schema = {}
  if (name) {
    schema.name = new RegExp(name)
  }
  if (fileName) {
    schema.fileName = new RegExp(fileName)
  }
  if (time) {
    time = time.split(',')
    schema.createTime = { $gte: new Date(time[0]), $lte: new Date(time[1]) }
  }
  console.log(schema);
  let data = await obtainEvidenceModel.find(schema)
  res.send({
    code: 200,
    data,
    msg: "存证信息获取成功"
  })
})

//图片上传
router.post('/uploadImg', (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, formData, imgData) => {
    console.log(imgData);
    res.send("http://localhost:8000/" + imgData.file[0].path)
  })
})

// 认证
router.post('/authentication', async (req, res) => {
  let body = req.body
  let { _id, ...re } = body
  console.log(re);
  if (re.code) {
    let li = await enterpriseCertificationModel.create(re)
    console.log((li._id).toString());
    await LoginModel.updateOne({ _id: _id }, { enterpriseId: (li._id).toString() })
    res.send({ code: 200, msg: '企业认证成功' })
  } else {
    let li = await codeidModel.create(re)
    console.log((li._id).toString());
    await LoginModel.updateOne({ _id: _id }, { CodeId: (li._id).toString() })
    res.send({ code: 200, msg: '个人认证成功' })
  }
})
// 套餐添加
router.post('/packageAdd', async (req, res) => {
  let body = req.body
  let package = await packageModel.create(body)

  res.send({
    code: 200,
    msg: '套餐添加成功',
    data: package
  })
})
// 套餐修改
router.post('/packageUpd', async (req, res) => {
  let body = req.body
  let { _id, ...re } = body
  let package = await packageModel.updateOne({ _id: _id }, { ...re })
  res.send({
    code: 200,
    msg: '套餐修改成功',
    data: package
  })
})
// 套餐删除
router.post('/packageDel', async (req, res) => {
  let _id = req.body._id
  let package = await packageModel.deleteOne({ _id: _id })
  res.send({
    code: 200,
    msg: '套餐修改成功',
  })
})
// 套餐查询
router.get('/packageList', async (req, res) => {
  let name = req.query.name
  let type = req.query.type
  let parms = {}
  if (name) {
    console.log(1);
    parms.name = new RegExp(name)
  }
  if (type) {
    console.log(2);
    parms.type = type
  }

  console.log(parms);
  let package = await packageModel.find(parms)

  res.send({
    code: 200,
    msg: '套餐列表查询成功',
    data: package
  })
})

// 订单添加
router.post('/orderAdd', async (req, res) => {
  let body = req.body
  let package = await packageModel.findOne({ _id: body.id })
  let a
  if (package != null) {
    a = { num: package.num, type: package.type, price: package.price,user:body.user }
    let typename = await existingEviTypeModel.findOne({name:'司法存证'})
    if(a.type == typename._id.toString()){
      let JuddepositNum = await LoginModel.findOne({_id:a.user})
      console.log(JuddepositNum,'111111111111111111111111111111111111111111');
      let uploginNum = await LoginModel.updateOne({_id:a.user},{Juddeposit:Number(JuddepositNum.Juddeposit)+Number(a.num)})
    }else{
      let OrdpositNum = await LoginModel.findOne({_id:a.user})
      let uploginNum = await LoginModel.updateOne({_id:a.user},{Ordposit:Number(OrdpositNum.Ordposit)+Number(a.num)})
    }
  } else {
    a = { num: body.num, type: body.type, price: body.price,user:body.user }
    let typename = await existingEviTypeModel.findOne({name:'司法存证'})
    if(a.type == typename._id.toString()){
      let JuddepositNum = await LoginModel.findOne({_id:a.user})
      let uploginNum = await LoginModel.updateOne({_id:a.user},{Juddeposit:Number(JuddepositNum.Juddeposit)+Number(a.num)})
    }else{
      let OrdpositNum = await LoginModel.findOne({_id:a.user})
      let uploginNum = await LoginModel.updateOne({_id:a.user},{Ordposit:Number(OrdpositNum.Ordposit)+Number(a.num)})
    }
  }

  let order = await orderModel.create(a)
  
  res.send({
    code: 200,
    msg: '订单添加成功',
    data: order
  })
})
// 订单修改
router.post('/orderUpd', async (req, res) => {
  let body = req.body
  let { _id, ...re } = body
  let order = await orderModel.updateOne({ _id: _id }, { ...re })
  res.send({
    code: 200,
    msg: '订单修改成功',
    data: order
  })
})
// 订单删除
router.post('/orderDel', async (req, res) => {
  let _id = req.body._id
  let order = await orderModel.deleteOne({ _id: _id })
  res.send({
    code: 200,
    msg: '订单修改成功',
  })
})

//时间戳转换
function formatTimestamp(timestamp) {
  const date = new Date(timestamp); // 使用时间戳创建 Date 对象

  const year = date.getFullYear(); // 年份
  const month = date.getMonth() + 1; // 月份，注意要加 1，因为月份从 0 开始计数
  const day = date.getDate(); // 日期
  const hours = date.getHours(); // 小时
  const minutes = date.getMinutes(); // 分钟
  const seconds = date.getSeconds(); // 秒钟

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


// 订单查询
router.get('/orderList', async (req, res) => {
  let time = req.query.time
  time = time?.split(',')
  console.log(time);
  if (time) {
    var startTime = new Date(time[0])
    var endTime = new Date(time[1])
  }

  let code = req.query.code
  let type = req.query.type
  let parms = {}

  let start = formatTimestamp(startTime)
  console.log(start);
  let end = formatTimestamp(endTime)
  console.log(end,);


  if (startTime && endTime) {
    parms.createTime = { $gte: start, $lte: end }
  }

  if (type) {
    parms.type = type
  }
  console.log(parms);
  let data = await orderModel.find(parms)
  res.send({
    code: 200,
    msg: '订单列表查询成功',
    data
  })
})

module.exports = router;